
import json

# import file_util
try:
    from top.starp.util import file_util
except Exception as e:
    print(e)
    import file_util
    import list_util


def json_obj_to_str(json_obj):
    json_str=json.dumps(json_obj)
    return json_str


def file_path_to_dict(filepath):
    #  file = open(path, encoding='gb18030'）
#   
    string=file_util.read_file_try(filepath)
    # try:
    #     with open(filepath, "r",encoding="utf-8") as fp:
    #         string=fp.read()
    # except Exception as e:
    #     print(e)
    #     print("filepath")
    #     print(filepath)
    #     with open(filepath, "r",encoding="gbk") as fp:
    #         string=fp.read()
    dict_data = json.loads(string)
    return dict_data
    #     json.dump(json_obj, fp)
    # country = '{"name": "United States", "population": 331002651}'
    # country_dict = json.loads(country)


def str_to_json_obj(json_str):
    return json.loads(json_str)
   
# def json_to_file(json_obj,filename):
#     # file_util.check_and_move_file()
#     file_util.check_and_create_file_parent_dir(filename)
#     with open(filename, "w") as fp:
#         json.dump(json_obj, fp)
#         # str to json python


def json_to_file(json_obj,filename,encoding="utf-8",need_zh=True,ensure_ascii=False,do_write=True):
    # utf8_json = json.dumps(json_obj, ensure_ascii=False)
    # file_util.check_and_move_file()
    if need_zh:
        ensure_ascii=False
        
    file_util.check_and_create_file_parent_dir(filename)
    print("filename",filename)
    if not do_write:
        return
    with open(filename, "w",encoding=encoding) as fp:
        json.dump(json_obj, fp,ensure_ascii=ensure_ascii)
        # str to json python

import json
import csv

def json_list_to_csv(data_list,csvPath):
    # 2.提出表头和表的内容
    # data_list = json.load(json_fp)
    file_util.check_and_create_file_parent_dir(csvPath)
    csv_fp = open(csvPath, "w",encoding='utf-8',newline='')
    first= data_list[0]
    # print("first",first)
    sheet_title = first.keys()
    # sheet_title = {"姓名","年龄"}  # 将表头改为中文
    sheet_data = []
    for data in data_list:
        sheet_data.append(data.values())

    # 3.csv 写入器
    writer = csv.writer(csv_fp)

    # 4.写入表头
    writer.writerow(sheet_title)

    # 5.写入内容
    writer.writerows(sheet_data)

    # 6.关闭两个文件
    # json_fp.close()
    csv_fp.close()

import os
import json

def read_json_files(folder_path):
    # list_util. 
    
    # app 
    data = []
    for file_name in os.listdir(folder_path):
        if file_name.endswith('.json'):
            file_path = os.path.join(folder_path, file_name)
            json_data=file_path_to_dict(file_path)
            if type(json_data)==list:
                for item in json_data:
                    data.append(item)
            elif type(json_data)==dict:
                data.append(json_data)
            # with open(file_path, 'r') as file:
            #     json_data = json.load(file)
            #     data.append(json_data)
    return data

# # 指定文件夹路径
# folder_path = '/path/to/folder'

# # 读取文件夹中的所有 JSON 文件
# json_data_list = read_json_files(folder_path)

# # 输出结果
# for json_data in json_data_list:
#     print(json_data)


"""
需求：将json中的数据转换成csv文件
"""
def json_to_csv(jsonPath,csvPath):
    # 1.分别 读，创建文件
    # json_fp = open("word.json", "r",encoding='utf-8')
    # csv_fp = open("word.csv", "w",encoding='utf-8',newline='')
    dataList=file_path_to_dict(jsonPath)
    return    json_list_to_csv(dataList,csvPath)

    # json_fp = open(jsonPath, "r",encoding='utf-8')
    # csv_fp = open(csvPath, "w",encoding='utf-8',newline='')

    # # 2.提出表头和表的内容
    # data_list = json.load(json_fp)
    # sheet_title = data_list[0].keys()
    # # sheet_title = {"姓名","年龄"}  # 将表头改为中文
    # sheet_data = []
    # for data in data_list:
    #     sheet_data.append(data.values())

    # # 3.csv 写入器
    # writer = csv.writer(csv_fp)

    # # 4.写入表头
    # writer.writerow(sheet_title)

    # # 5.写入内容
    # writer.writerows(sheet_data)

    # # 6.关闭两个文件
    # json_fp.close()
    # csv_fp.close()

# D:\file\图书联盟
if __name__ == "__main__":
    # csv_json()
    pass
    dir_name=rf'D:\file\图书联盟'
    csv_out_path=rf"/file/csvcsv图书联盟/图书联盟.csv"
    lst=read_json_files(dir_name)
    # json_to_csv()
    # json_list_to_csv(lst,csv_out_path)
    file_util.to_csv(lst,csv_out_path)
